//
//  CJImageDownloader.swift
//  AHQBookRead
//
//  Created by lidi on 2017/10/29.
//  Copyright © 2017年 ahq. All rights reserved.
//

import UIKit

class CJImageDownloader: NSObject {

    static let shared = CJImageDownloader()
    
    func download(imageUrl:String,callBack:(()->Void)?) {
        DispatchQueue.global().async {
            let cachePath = FileManager.default.cachePathFor(userId: "test")
            let imageDir = cachePath + "/epubImages/"
            
            if !FileManager.default.fileExists(atPath: imageDir, isDirectory: nil) {
                try? FileManager.default.createDirectory(atPath: imageDir, withIntermediateDirectories: true, attributes: nil)
            }

            let imageDataPath = imageDir + imageUrl.md5()
            
            if let imageURL = URL(string: imageUrl) {
                if let imageData = try? Data(contentsOf: imageURL) {
                    let cacheUrl = URL(fileURLWithPath:imageDataPath)
                    try? imageData.write(to: cacheUrl)
                    callBack?()
                }
            }
        }
        
    }
    
    func fetchImage(imageUrl:String) -> UIImage? {
        let cachePath = FileManager.default.cachePathFor(userId: "test")
        let imageDataPath = cachePath + "/epubImages/" + imageUrl.md5()
        
        if let image = UIImage(contentsOfFile: imageDataPath) {
            return image
        } else {
            return nil
        }
    }
    
}
